//
//  playerTableViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 16/8/23.
//  Copyright © 2016年 宋旭东. All rights reserved.
//
#import "playerTableViewController.h"
#import "playerPayViewController.h"
#import "userInformationViewController.h"
#import "playerWorkViewCell.h"
#import "playRequestModel.h"
#import "CommentTableViewCell.h"
#import "CommentListModel.h"
#import "UIViewExt.h"
#import "AppDelegate.h"
#import "MMDrawerController.h"
#import "DownSheet.h"
#import "DownSheetModel.h"
#import "JCAlertView.h"
#import "WXApi.h"
#import "UIImage+thumbImage.h"
#import "MJRefresh.h"
#import "LCActionSheet.h"
#define NavigationBar_HEIGHT 44

static playerTableViewController *player = nil;

@interface playerTableViewController ()<DownSheetDelegate,MJRefreshBaseViewDelegate, UITextFieldDelegate, LCActionSheetDelegate>
{
    int page;
    int lastPage;
    int pages;
//    MJRefreshHeaderView *header; 
    MJRefreshFooterView *fotter;
    NSString *selfAvatar;
    NSString *selfName;
    NSString *selfID;
    BOOL _isCusAnimation;
}
@property (strong, nonatomic) NSMutableArray *deletSheetArray;
@property (strong, nonatomic) NSArray *SheetArray;
@property (strong, nonatomic) playRequestModel *playRequest;



@end

@implementation playerTableViewController
#pragma mark - 
#pragma makr 初始化方法
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        self.view.backgroundColor = [UIColor whiteColor];
    }
    return self;
}
+(playerTableViewController *)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[playerTableViewController alloc] init];
    });
    return player;
}
- (void)initSheetData
{
    DownSheetModel *Model_1 = [[DownSheetModel alloc]init];
    Model_1.icon = @"player-fuzhi.png";
    Model_1.icon_on = @"player-fuzhi.png";
    Model_1.title = @"复制链接";
    DownSheetModel *Model_3 = [[DownSheetModel alloc]init];
    Model_3.icon = @"Trash";
    Model_3.icon_on = @"Trash";
    Model_3.title = @"删除";
    DownSheetModel *Model_4 = [[DownSheetModel alloc]init];
    Model_4.icon = @"close";
    Model_4.icon_on = @"close";
    Model_4.title = @"取消";
    DownSheetModel *Model_5 = [[DownSheetModel alloc]init];
    Model_5.icon = @"exclamation";
    Model_5.icon_on = @"exclamation";
    Model_5.title = @"举报";
    DownSheetModel *Model_7 = [[DownSheetModel alloc]init];
    Model_7.icon = @"play_more_close.png";
    Model_7.icon_on = @"play_more_close.png";
    Model_7.title = @"仅自己";
    DownSheetModel *Model_8 = [[DownSheetModel alloc]init];
    Model_8.icon = @"play_more_open.png";
    Model_8.icon_on = @"play_more_open.png";
    Model_8.title = @"公开";
    DownSheetModel *Model_2 = [[DownSheetModel alloc]init];
    Model_2.icon = @"UMS_wechat_timeline_icon@2x.png";
    Model_2.icon_on = @"UMS_wechat_timeline_icon@2x.png";
    Model_2.title = @"朋友圈";
    DownSheetModel *Model_6 = [[DownSheetModel alloc]init];
    Model_6.icon = @"UMS_wechat_icon@2x.png";
    Model_6.icon_on = @"UMS_wechat_icon@2x.png";
    Model_6.title = @"微信好友";
    DownSheetModel *Model_9 = [[DownSheetModel alloc] init];
    Model_9.icon = @"UMS_sina_icon.png";
    Model_9.icon_on = @"UMS_sina_icon.png";
    Model_9.title = @"新浪微博";
    if (_isPrivate) {
        self.deletSheetArray = [[NSMutableArray alloc] initWithObjects:Model_2,Model_6,Model_9,Model_1, Model_8,Model_3, Model_4, nil];
    } else {
        self.deletSheetArray = [[NSMutableArray alloc] initWithObjects:Model_2,Model_6,Model_9,Model_1, Model_7, Model_3, Model_4, nil];
    }
    self.SheetArray = [[NSArray alloc] initWithObjects:Model_2,Model_6,Model_9,Model_1, Model_5, Model_4, nil];
    
}
- (void)reloadViews:(Player_ShowModel *)playModel
{
    [self createTableview];
    self.uid = [playModel.user valueForKey:@"uid"];
    _header.workID = self.workID;
    _header.waveform = self.waveform;
    [_header reloadViews:playModel];
    self.qiniuPlayUrlStr = playModel.tmpfile;
    self.title = playModel.title;
    [self initSheetData];
    self.commentListArray = [[NSMutableArray alloc] init];
    page = 1;
    [self AFNetworking:page refreshing:nil];
}
-(void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backToThePrevious:) name:@"stopAudioPlayer" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopAudioPlayer) name:@"stopAudioBeforRecord" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goToSelfVC:) name:@"commentListGoToSelf" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goToOtherVC:) name:@"commentListGoToOther" object:nil];
    [self createNavButton];
    [self createTableview];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [MobClick beginLogPageView:@"播放"];
    self.navigationController.navigationBar.translucent = NO;
    if (_header.streamer.currentTime <= 0 && _header.streamer.status != DOUAudioStreamerIdle) {
        [_header.showImage setImage:[UIImage imageNamed:@"bigPlaceholderimage"]];
        [_header.playerControlButton setBackgroundImage:[UIImage imageNamed:@"Play_loading"] forState:UIControlStateNormal];
    }
    
    [AppDelegate shareDelegate].playerStateBtn.hidden = YES;
//    if (_commentView) {
//        _commentView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 64 - 45, self.view.frame.size.width, 45);
//    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
//    _shouldPlayNextWork = YES;
    [_playRequest requestComment:_header workID:self.workID];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    [AppDelegate shareDelegate].indicator.state = NAKPlaybackIndicatorViewStatePlaying;
    [[AppDelegate shareDelegate] setUpMusicIndicator];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [MobClick endLogPageView:@"播放"];
    [AppDelegate shareDelegate].playerStateBtn.hidden = NO;
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    if (_header.streamer.status != DOUAudioStreamerPlaying) {
        [AppDelegate shareDelegate].indicator.state = NAKPlaybackIndicatorViewStatePaused;
        [[AppDelegate shareDelegate] setUpMusicIndicator];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
//    _shouldPlayNextWork = NO;
    //    [AppDelegate shareDelegate].isPlayerVC = [NSNumber numberWithBool:NO];
}
- (void)createNavButton
{
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setFrame:CGRectMake(0, 0, 30, 30)];
    [back setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backToThePrevious:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backItem;
    
    self.more = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    _more.image = [UIImage imageNamed:@"Play_more"];
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showMenu:)];
    [_more addGestureRecognizer:recognizer];
    UIBarButtonItem *userItem = [[UIBarButtonItem alloc] initWithCustomView:_more];
    self.navigationItem.rightBarButtonItem = userItem;
}
- (void)createTableview
{
    if (!_tableview) {
        self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - NavigationBar_HEIGHT * 2 - 20) style:UITableViewStylePlain];
        _tableview.dataSource = self;
        _tableview.delegate = self;
        _tableview.showsVerticalScrollIndicator = NO;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.separatorColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
        [self.view addSubview:_tableview];
        fotter = [MJRefreshFooterView footer];
        fotter.scrollView = _tableview;
        fotter.delegate = self;
        [self createTableviewHeader];
        self.commentField  = [[Play_commentView alloc] initWithFrame:CGRectMake(0, _tableview.bottom, self.view.frame.size.width, NavigationBar_HEIGHT)];
        _commentField.comment.delegate = self;
        _commentField.send.hidden = NO;
        [_commentField.send addTarget:self action:@selector(hideKeyBord:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_commentField];

    } else {
        [self createTableviewHeader];
    }
}
- (void)createTableviewHeader
{
    if (!_header) {
        self.header = [[playerTableviewHeader alloc] initWithFrame:CGRectMake(0, 0, self.view.width, _tableview.height + 5)];
        _tableview.tableHeaderView = _header;
    } else {
        
    }
    __weak playerTableViewController *weakSelf = self;
    _header.userBlock = ^(){
        [weakSelf goToUserInfo];
    };
    _header.payBlock = ^(NSString *workId, UIImage *firstImage, NSArray *tags, NSArray *priceArray, NSString *price, NSString *loveCount, NSString *commentCount){
//        NSLog(@"%@\n%@\n%@\n%@",workId,firstImage,tags,price);
        [weakSelf goToPayControllerWithWorkid:workId cover:firstImage tags:tags priceArray:priceArray price:price title:weakSelf.title loveCount:loveCount contentCount:commentCount];
    };
    __weak UITableView *weakTable = _tableview;
    _header.commentBlock = ^(){
        [weakTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    };
}
#pragma mark - 
#pragma mark 点击事件
- (void)goToPayControllerWithWorkid:(NSString *)workid cover:(UIImage *)cover tags:(NSArray *)tags priceArray:(NSArray *)priceArray price:(NSString *)price title:(NSString *)title loveCount:(NSString *)loveCount contentCount:(NSString *)contentCount
{
    playerPayViewController *playerPay = [[playerPayViewController alloc] initWithworkName:title priceArray:priceArray price:price tags:tags loveCount:loveCount commentCount:contentCount cover:cover workid:workid];
    [self.navigationController pushViewController:playerPay animated:YES];
}
- (void)goToUserInfo{
//    [self.navigationController stop];
    MMDrawerController *drawer = (MMDrawerController *)[AppDelegate shareDelegate].window.rootViewController;
    
    if ([self.uid isEqualToString:[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"]]) {
//        [_streamer stop];
        [drawer closeDrawerAnimated:YES completion:^(BOOL finished) {
            [self.navigationController popToRootViewControllerAnimated:NO];
        }];
        UITabBarController *tab = (UITabBarController *)drawer.centerViewController;
        tab.selectedIndex = 4;
    } else {
//        [self backToThePrevious:nil];
        //发出通知
        userInformationViewController *otheruser = [[userInformationViewController alloc] initWithSelfUid:_uid];
        otheruser.isNeedPush = NO;
        //        UITabBarController *tab = (UITabBarController *)drawer.centerViewController;
        //        UINavigationController *nav= (UINavigationController *)tab.selectedViewController;
        [self.navigationController pushViewController:otheruser animated:YES];
        //        [self.navigationController pushViewController:otheruser animated:YES];
    }
}
- (void)stopAudioPlayer{
    if ([_header.streamer status] == DOUAudioStreamerPlaying) {
        [_header.streamer stop];
    }
}
- (void)backToThePrevious:(UIButton *)sender{
//        [self stopAudioPlayer];
//    //
//    //    [self.navigationController stop];
//        [_header.playerControlButton setBackgroundImage:nil forState:UIControlStateNormal];
//        [_header.rolling removeTrajectoryarrayAllObject];
//        [_header.rolling removeFromSuperview];
//        _header.rolling = nil;
//        [_header.timer setFireDate:[NSDate distantFuture]];
    if ([_commentField.comment isFirstResponder]) {
//        _commentField.send.hidden = YES;
        _commentField.frame = CGRectMake(0, _tableview.bottom, self.view.frame.size.width, NavigationBar_HEIGHT);
        [_commentField.comment resignFirstResponder];
    }
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    MMDrawerController *drawer = (MMDrawerController *)[AppDelegate shareDelegate].window.rootViewController;
    [drawer closeDrawerAnimated:YES completion:^(BOOL finished) {
        //        [self _cancelStreamer];
    }];
}
- (void)showMenu:(UIButton *)sender
{
//    [self send:_commentView.send];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaults valueForKey:@"uid"];
    if ([self.uid isEqualToString:uid]) {
        _isSelf = YES;
        DownSheet *sheet = [[DownSheet alloc]initWithlist:_deletSheetArray height:0];
        sheet.delegate = self;
        [sheet showInViewController:nil];
    } else {
        _isSelf = NO;
        DownSheet *sheet = [[DownSheet alloc]initWithlist:_SheetArray height:0];
        sheet.delegate = self;
        [sheet showInViewController:nil];
    }
}
-(void)didSelectIndex:(NSInteger)index{
    UIPasteboard *paste = [UIPasteboard generalPasteboard];
    UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
    customView.backgroundColor = [UIColor whiteColor];
    customView.text = @"复制成功!";
    customView.textAlignment = NSTextAlignmentCenter;
    customView.layer.borderColor = [[UIColor blackColor] CGColor];
    customView.layer.borderWidth = 2;
    JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaults valueForKey:@"uid"];
    if ([self.uid isEqualToString:uid]) {
        switch (index) {
            case 0:
                [self shareToWXTimeline];
                break;
            case 1:
                [self shareToWXSession];
                break;
            case 2:
                [self shareToSina];
                break;
            case 3:
                paste.string = [NSString stringWithFormat:@"http://www.pillele.cn/play.php?id=%@", _workID];
                [_alert show];
                [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
                break;
            case 4:
                [self setPrivateStatue];
                break;
            case 5:
                [self deleteWorkOrReport];
            default:
                break;
        }
    } else {
        switch (index) {
            case 0:
                [self shareToWXTimeline];
                break;
            case 1:
                //微信
                [self shareToWXSession];
                break;
            case 2:
                [self shareToSina];
                break;
            case 3:
                paste.string = [NSString stringWithFormat:@"http://www.pillele.cn/play.php?id=%@", _workID];
                [_alert show];
                [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
                break;
            case 4:
                [self deleteWorkOrReport];
            default:
                break;
        }
    }
}
- (void)shareToSina
{
    AppDelegate *myDelegate = [AppDelegate shareDelegate];
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = kRedirectURI;
    authRequest.scope = @"all";
    
    WBMessageObject *message = [WBMessageObject message];
    message.text =[NSString stringWithFormat:@"《%@》来 #声音实验室# 听 %@ 的更多作品 %@",self.title, _header.userNameLabel.text,[NSString stringWithFormat:@"http://www.pillele.cn/play.php?id=%@", _workID]];
    
    UIImage *thumbImage = (UIImage *)[self.header.showImageArray firstObject];
    
    WBImageObject *object = [WBImageObject object];
    object.imageData = UIImageJPEGRepresentation(thumbImage, 1);
    message.imageObject = object;
    //
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:authRequest access_token:myDelegate.wbtoken];
    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}
- (void)shareToWXTimeline
{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = [NSString stringWithFormat:@"%@｜声音实验室",self.title];
    message.description = [NSString stringWithFormat:@"来声音实验室听 %@ 的更多作品",_header.userNameLabel.text];
    
    UIImage *thumbImage = [UIImage generatePhotoThumbnail:(UIImage *)[_header.showImageArray firstObject]];
    
    [message setThumbImage:thumbImage];
    WXMusicObject *ext = [WXMusicObject object];
    ext.musicUrl = [NSString stringWithFormat:@"http://www.pillele.cn/play.php?id=%@", _workID];//@"";
    ext.musicDataUrl = _qiniuPlayUrlStr;
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    //    req.text = @"aaaaaaaaa"
    req.bText = NO;
    req.message = message;
    req.scene = 1;
    [WXApi sendReq:req];
    //    NSLog(@"%d",result);
}
- (void)shareToWXSession
{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = [NSString stringWithFormat:@"%@｜声音实验室",self.title];
    message.description = [NSString stringWithFormat:@"来声音实验室听 %@ 的更多作品",_header.userNameLabel.text];
    UIImage *thumbImage = [UIImage generatePhotoThumbnail:(UIImage *)[_header.showImageArray firstObject]];
    [message setThumbImage:thumbImage];
    WXMusicObject *ext = [WXMusicObject object];
    ext.musicUrl = [NSString stringWithFormat:@"http://www.pillele.cn/play.php?id=%@", _workID];//@"";
    ext.musicDataUrl = _qiniuPlayUrlStr;
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = 0;
    
    [WXApi sendReq:req];
}
//删除或举报
- (void)deleteWorkOrReport
{
    if (_isSelf == YES) {
        [JCAlertView showTwoButtonsWithTitle:@"警告" Message:@"是否删除该作品" ButtonType: JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:^{
            
        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
//            [_playRequest deleteWork:self workid:_idStr];
        }];
    } else {
        //举报
    }
}
//公开或仅自己
- (void)setPrivateStatue
{
    if (_isPrivate) {
        [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"确定将作品设为公开?" ButtonType: JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:^{
            
        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
//            [_playRequest private:self workid:_idStr];
        }];
    } else {
        [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"确定将作品设为尽自己可见?" ButtonType: JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:^{
            
        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
//            [_playRequest private:self workid:_idStr];
        }];
    }
}
#pragma mark -
#pragma mark ---------------评论列表
- (void)isCusAnimation:(BOOL)isCusAnimation
{
    _isCusAnimation = isCusAnimation;
}


#pragma mark tableview 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _commentListArray.count;
}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    if (section == 0) {
//        
//    }
//}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//    return 3;
//}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_commentListArray.count > 0) {
        CommentListModel *model = _commentListArray[indexPath.row];
        UIFont *contentFont = [UIFont systemFontOfSize:14];
        NSString *contentStr;
        if (model.tousername.length > 0) {
            contentStr = [NSString stringWithFormat:@"@%@：%@",model.tousername,model.content];
        } else {
            contentStr = model.content;
        }
        CGRect rect = [contentStr boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 50 - 2 * (([UIScreen mainScreen].bounds.size.height - 64 - 45) / 8 - 24), MAXFLOAT)//限制最大的宽度和高度
                                               options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  |NSStringDrawingUsesLineFragmentOrigin//采用换行模式
                                            attributes:@{NSFontAttributeName:contentFont}//传人的字体字典
                                               context:nil];
        //        float toUserNameH;
        float cellH = ([UIScreen mainScreen].bounds.size.height - 64 - 45) / 8;
        float cellHeight = cellH/2 + 5 + rect.size.height + 12;
        if (cellHeight < cellH) {
            return cellH;
        } else {
            return cellHeight;
        }
    } else {
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"comment";
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[CommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_commentListArray.count > 0) {
        cell.model = _commentListArray[indexPath.row];
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentListModel *mo =  _commentListArray[indexPath.row];
    if ([mo.user_id isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]]) {
        LCActionSheet *deleteSheet = [[LCActionSheet alloc] initWithTitle:@"删除我的评论" buttonTitles:@[@"删除"] redButtonIndex:0 delegate:self];
        deleteSheet.tag = mo.id.integerValue;
        [deleteSheet show];
        self.delIndexPath = indexPath;
        [self hideKeyBord:_commentField.send];
    } else  {
        [_commentField.comment becomeFirstResponder];
        _commentField.comment.placeholder = [NSString stringWithFormat:@"@%@", mo.username];
        _commentField.fid = mo.user_id;
        _commentField.timeline = mo.timeline;
        _commentField.toUserName = mo.username;
    }
}
- (void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self deleteComment:[NSString stringWithFormat:@"%d", actionSheet.tag]];
        [_commentListArray removeObjectAtIndex:_delIndexPath.row];
    }
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        fotter.hidden = NO;
        [_commentListArray removeAllObjects];
        [self AFNetworking:page refreshing:refreshView];
    } else { // 上拉加载更多
        if (pages == 1 || page == pages) {
            fotter.hidden = YES;
        } else {
            page++;
            [self AFNetworking:page refreshing:refreshView];
        }
    }
}
- (void)AFNetworking:(int)pag refreshing:(MJRefreshBaseView *)refreshView
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/comment/%@/commentlist?p=%d", _workID, pag];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *bigDic = responseObject;
        NSDictionary *dic = [bigDic valueForKey:@"data"];
        for (NSDictionary *dict in dic) {
            CommentListModel *model = [[CommentListModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [_commentListArray addObject:model];
        }
        NSDictionary *meta = [bigDic valueForKey:@"meta"];
        if (meta != nil) {
//            self.title = [NSString stringWithFormat:@"评论: %@",[meta valueForKey:@"total"]];
            selfID = [meta valueForKey:@"uid"];
            selfAvatar = [meta valueForKey:@"avatar"];
            selfName = [meta valueForKey:@"username"];
            pages = [[meta valueForKey:@"pages"] intValue];
            if (pages == 1 || pag == pages) {
                fotter.hidden = YES;
            }
        }
        if (_tableview) {
            [_tableview reloadData];
        }
        [refreshView endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [refreshView endRefreshing];
    }];
}
-(void)keyboardWillShow:(NSNotification *)notification
{
    if ([AppDelegate shareDelegate].isForeground.boolValue == YES) {
        NSDictionary *userInfo = [notification userInfo];
        NSTimeInterval animationDuration;
        UIViewAnimationCurve animationCurve;
        CGRect keyboardEndFrame;
        
        [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
        [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
        [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:animationDuration];
        [UIView setAnimationCurve:animationCurve];
        if (notification.name == UIKeyboardWillShowNotification) {
//            if ([_commentField.comment isFirstResponder]) {
            _commentField.hidden = NO;
            _commentField.frame = CGRectMake(0, self.view.height - keyboardEndFrame.size.height - 45, self.view.width, 45);
//  }
        } else {
            _commentField.frame = CGRectMake(0, _tableview.bottom, self.view.frame.size.width, NavigationBar_HEIGHT);
        }
        [UIView commitAnimations];
        //处理移动事件，将各视图设置最终要达到的状态
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    Play_commentView *commentView = (Play_commentView *)textField.nextResponder;
    if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
        return YES;
    } else {
        
        if ([string isEqualToString:@"\n"] && textField.text.length > 0) {
            NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/comment/%@/add", _workID];
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            NSString *userHeader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
            [manager.requestSerializer setValue:userHeader forHTTPHeaderField:@"authorization"];
            
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString *user_id = [user objectForKey:@"uid"];
            
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:textField.text, @"content", user_id, @"user_id", commentView.timeline, @"timeline", commentView.fid, @"f_id",nil];
            if (dic != nil) {
                [manager POST:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                    count
                    CommentListModel *model = [[CommentListModel alloc] init];
                    model.avatar = selfAvatar;
                    model.content = _commentField.comment.text;
                    model.tousername = commentView.toUserName;
                    model.username = selfName;
                    model.user_id = selfID;
                    model.reviewtime = @"一秒前";
                    model.id = [NSString stringWithFormat:@"%@",[responseObject valueForKey:@"commentid"]];
                    [_commentListArray insertObject:model atIndex:0];
                    [_tableview reloadData];
                    _commentField.comment.text = nil;
                    [_header loadLikeCount:_header.love_count commentCount:[responseObject valueForKey:@"count"]];
                    [self hideKeyBord:nil];
//                    PlayerViewController *player =(PlayerViewController *)[self.navigationController.viewControllers firstObject];
                    Comment *comment = [[Comment alloc] init];
                    comment.avatar = [[[NSUserDefaults standardUserDefaults] objectForKey:@"myDictionary"] valueForKey:@"avatar"];
                    comment.comment = [dic valueForKey:@"content"];
                    comment.timeLine = [dic valueForKey:@"timeline"];
                    [self.header.rolling createDanmuItem:comment];
                    if ([self.header.streamer status] == DOUAudioStreamerPaused) {
                        [self.header.rolling pauseAnimation];
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                    NSLog(@"111");
                }];
            }
            
        } else {
            
        }
        return YES;
    }
    
}
- (void)deleteComment:(NSString *)commentID
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/comment/%@/del", commentID];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *userHeader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:userHeader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [_tableview reloadData];
        [_header loadLikeCount:_header.love_count commentCount:[responseObject valueForKey:@"count"]];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)hideKeyBord:(UIButton *)sender
{
    [_commentField.comment resignFirstResponder];
}
- (void)goToSelfVC:(NSNotification *)notification
{
//    PlayerViewController *player =(PlayerViewController *)[self.navigationController.viewControllers firstObject];
//    [player backToThePrevious:nil];
    
    MMDrawerController *drawer = (MMDrawerController *)[AppDelegate shareDelegate].window.rootViewController;
    [drawer closeDrawerAnimated:YES completion:^(BOOL finished) {
        [self.navigationController popToRootViewControllerAnimated:NO];
    }];
    
    UITabBarController *tab = (UITabBarController *)drawer.centerViewController;
    tab.selectedIndex = 4;
}
- (void)goToOtherVC:(NSNotification *)notification
{
    CommentListModel *model = notification.object;
    userInformationViewController *otheruser = [[userInformationViewController alloc] initWithSelfUid:model.user_id];
    otheruser.isNeedPush = NO;
    [self.navigationController pushViewController:otheruser animated:YES];
}
@end
